import zh from './zh.js';
import en from './en.js';

const translations = {
  'zh':zh,
  'en':en
};
let currentLocale = 'en';

function getTranslations(locale) {
  return translations[locale] || en;
}

let translation = getTranslations(currentLocale);


function translate(template, replacements) {

  // console.log('#i18n', template, replacements);

  // Translate
  let msg = translation[template] || template;

  if (template == msg) {
    console.warn(
      '#i18n No translation for "' + template + '" , replacements:',
      replacements || 'none'
    );
  }

  replacements = replacements || {};

  // Replace
  msg = msg.replace(/{([^}]+)}/g, function(_, key) {
    return replacements[key] || '{' + key + '}';
  });

  // console.log('#i18n return', msg);
  return msg;
}

export function getLocale() {
  return currentLocale;
}

export function setLocale(newLocale) {
  if (translations[newLocale]) {
    currentLocale = newLocale;
    translation = getTranslations(currentLocale);
    return true;
  }
  return false;
}

export const translateModule = {
  translate: [ 'value', translate ]
};
